<template>
  <div class="ticket-detail-container">
    <el-card v-if="ticket" class="ticket-card">
      <!-- 工单头部信息 -->
      <template #header>
        <div class="ticket-header">
          <div class="ticket-title-section">
            <h2>{{ ticket.title }}</h2>
            <div class="ticket-meta">
              <el-tag :type="getStatusType(ticket.status)" size="large">
                {{ translateStatus(ticket.status) }}
              </el-tag>
              <el-tag :type="getPriorityType(ticket.priority)" size="large">
                {{ translatePriority(ticket.priority) }}
              </el-tag>
              <span class="ticket-number">#{{ ticket.ticketNumber || ticket.id }}</span>
            </div>
          </div>
          <div class="ticket-actions">
          <el-button 
              v-if="canUpdateStatus"
            type="primary" 
              @click="showStatusUpdateDialog"
            >
              <el-icon><Edit /></el-icon>
              更新状态
            </el-button>
            <el-button 
              v-if="canAssign"
              type="success" 
              @click="showAssignDialog"
            >
              <el-icon><User /></el-icon>
              分配工单
            </el-button>
            <el-button 
              v-if="canUpdatePriority"
              type="warning" 
              @click="showPriorityUpdateDialog"
            >
              <el-icon><Flag /></el-icon>
              更新优先级
          </el-button>
          </div>
        </div>
      </template>

      <!-- 工单详细信息 -->
      <div class="ticket-content">
        <el-row :gutter="24">
          <!-- 左侧主要内容 -->
          <el-col :span="16">
            <!-- 问题描述 -->
            <el-card class="section-card">
              <template #header>
                <h3>问题描述</h3>
              </template>
              <div class="description-content">
                {{ ticket.description }}
              </div>
              <div v-if="ticket.descriptionDetail" class="description-detail">
                <h4>详细描述</h4>
                <div class="detail-content">
                  {{ ticket.descriptionDetail }}
                </div>
              </div>
            </el-card>

            <!-- 评论区域 -->
            <el-card class="section-card">
              <template #header>
                <div class="comments-header">
                  <h3>评论 ({{ comments.length }})</h3>
                  <el-button type="primary" @click="showCommentDialog">
                    <el-icon><Plus /></el-icon>
                    添加评论
                  </el-button>
                </div>
              </template>
              
              <div class="comments-list">
                <div 
                  v-for="comment in comments" 
                  :key="comment.id"
                  class="comment-item"
                >
                  <div class="comment-header">
                    <div class="comment-author">
                      <el-avatar :size="32">{{ comment.author?.fullName?.charAt(0) || 'U' }}</el-avatar>
                      <div class="author-info">
                        <div class="author-name">{{ comment.author?.fullName || '未知用户' }}</div>
                        <div class="comment-time">{{ formatDate(comment.createdAt) }}</div>
                      </div>
                    </div>
                    <div class="comment-actions">
                      <el-button 
                        v-if="comment.isInternal" 
                        type="info" 
                        size="small"
                        disabled
                      >
                        内部评论
                      </el-button>
                      <el-button size="small" @click="likeComment(comment.id)">
                        <el-icon><ThumbUp /></el-icon>
                        {{ comment.likeCount || 0 }}
                      </el-button>
                    </div>
                  </div>
                  <div class="comment-content">
                    {{ comment.content }}
                  </div>
                  <div v-if="comment.isEdited" class="comment-edited">
                    已编辑于 {{ formatDate(comment.editedAt) }}
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧信息面板 -->
          <el-col :span="8">
            <!-- 工单信息 -->
            <el-card class="info-card">
              <template #header>
                <h3>工单信息</h3>
              </template>
              <el-descriptions :column="1" size="small">
                <el-descriptions-item label="工单编号">
                  {{ ticket.ticketNumber || 'TK' + ticket.id }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(ticket.status)">
            {{ translateStatus(ticket.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
                  <el-tag :type="getPriorityType(ticket.priority)">
            {{ translatePriority(ticket.priority) }}
          </el-tag>
        </el-descriptions-item>
                <el-descriptions-item label="创建者">
                  {{ ticket.createdBy?.fullName || '未知用户' }}
        </el-descriptions-item>
                <el-descriptions-item label="分配给">
                  {{ ticket.assignedTo?.fullName || '未分配' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(ticket.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(ticket.updatedAt) }}
        </el-descriptions-item>
                <el-descriptions-item v-if="ticket.resolvedAt" label="解决时间">
                  {{ formatDate(ticket.resolvedAt) }}
                </el-descriptions-item>
                <el-descriptions-item v-if="ticket.closedAt" label="关闭时间">
                  {{ formatDate(ticket.closedAt) }}
                </el-descriptions-item>
      </el-descriptions>
      </el-card>

            <!-- 工单历史 -->
            <el-card class="info-card">
        <template #header>
                <h3>工单历史</h3>
        </template>
              <el-timeline>
                <el-timeline-item
                  v-for="(history, idx) in ticketHistory"
                  :key="idx"
                  :timestamp="formatDate(history.createdAt)"
                  :type="getHistoryType(history.actionType)"
                >
                  <div class="history-content">
                    <strong>{{ history.description }}</strong>
                    <p v-if="history.oldValue && history.newValue">
                      {{ history.oldValue }} → {{ history.newValue }}
                    </p>
              </div>
                </el-timeline-item>
              </el-timeline>
            </el-card>

            <!-- 状态跟踪 -->
            <el-card class="info-card">
              <template #header>
                <h3>状态跟踪</h3>
              </template>
              <TicketStatusTracking 
                :ticket-id="ticketId"
                :show-filter="true"
                :auto-refresh="false"
              />
            </el-card>
          </el-col>
        </el-row>
        </div>
      </el-card>

    <!-- 状态更新对话框 -->
    <el-dialog v-model="statusDialog.visible" title="更新工单状态" width="500px">
        <el-form :model="statusForm" label-width="80px">
          <el-form-item label="新状态">
            <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="OPEN" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已关闭" value="CLOSED" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input 
              v-model="statusForm.note" 
              type="textarea" 
              :rows="3"
              placeholder="请输入处理备注（可选）"
            />
          </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="updating" @click="updateStatus">
          确定
            </el-button>
      </template>
    </el-dialog>

    <!-- 分配工单对话框 -->
    <el-dialog v-model="assignDialog.visible" title="分配工单" width="400px">
        <el-form label-width="80px">
        <el-form-item label="分配给">
            <el-select v-model="assignDialog.agentId" placeholder="选择技术人员">
              <el-option 
                v-for="agent in agents" 
                :key="agent.id" 
              :label="agent.fullName" 
                :value="agent.id" 
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="assignDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="assigning" @click="assignTicket">确认</el-button>
      </template>
    </el-dialog>

    <!-- 优先级更新对话框 -->
    <el-dialog v-model="priorityDialog.visible" title="更新工单优先级" width="400px">
      <el-form label-width="80px">
        <el-form-item label="优先级">
          <el-select v-model="priorityDialog.priority" placeholder="选择优先级">
            <el-option label="低" value="LOW" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="高" value="HIGH" />
            <el-option label="紧急" value="URGENT" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="priorityDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="updatingPriority" @click="updatePriority">确定</el-button>
        </template>
      </el-dialog>

    <!-- 添加评论对话框 -->
    <el-dialog v-model="commentDialog.visible" title="添加评论" width="600px">
      <el-form :model="commentForm" label-width="80px">
        <el-form-item label="评论内容">
          <el-input 
            v-model="commentForm.content" 
            type="textarea" 
            :rows="4"
            placeholder="请输入评论内容"
          />
        </el-form-item>
        <el-form-item label="评论类型">
          <el-radio-group v-model="commentForm.commentType">
            <el-radio label="PUBLIC">公开评论</el-radio>
            <el-radio label="INTERNAL">内部评论</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="commentDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="addingComment" @click="addComment">确定</el-button>
      </template>
      </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { TicketService } from '../services/tickets'
import { CommentService } from '../services/comments'
import { UserService } from '../services/users'
import { ElMessage } from 'element-plus'
import { Edit, User, Flag, Plus, ThumbUp } from '@element-plus/icons-vue'
import TicketStatusTracking from '../components/TicketStatusTracking.vue'

export default {
  name: 'TicketDetail',
  components: {
    TicketStatusTracking
  },
  setup() {
    const route = useRoute()
    const ticketId = route.params.id
    
    // 响应式数据
    const ticket = ref(null)
    const comments = ref([])
    const ticketHistory = ref([])
    const agents = ref([])
    const loading = ref(false)
    
    // 对话框状态
    const statusDialog = ref({ visible: false })
    const assignDialog = ref({ visible: false, agentId: null })
    const priorityDialog = ref({ visible: false, priority: null })
    const commentDialog = ref({ visible: false })
    
    // 表单数据
    const statusForm = ref({ status: '', note: '' })
    const commentForm = ref({ content: '', commentType: 'PUBLIC' })
    
    // 操作状态
    const updating = ref(false)
    const assigning = ref(false)
    const updatingPriority = ref(false)
    const addingComment = ref(false)

    // 权限检查（简化版）
    const canUpdateStatus = computed(() => true)
    const canAssign = computed(() => true)
    const canUpdatePriority = computed(() => true)

    // 加载工单详情
    const loadTicket = async () => {
      try {
        loading.value = true
        ticket.value = await TicketService.get(ticketId)
        await loadComments()
        await loadTicketHistory()
      } catch (error) {
        ElMessage.error('加载工单详情失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 加载评论
    const loadComments = async () => {
      try {
        comments.value = await CommentService.getTicketComments(ticketId)
      } catch (error) {
        console.error('加载评论失败:', error)
      }
    }

    // 加载工单历史
    const loadTicketHistory = async () => {
      try {
        // 这里应该调用工单历史API，暂时使用模拟数据
        ticketHistory.value = [
          {
            actionType: 'CREATED',
            description: '工单已创建',
            createdAt: ticket.value?.createdAt,
            oldValue: null,
            newValue: null
          }
        ]
      } catch (error) {
        console.error('加载工单历史失败:', error)
      }
    }

    // 加载技术人员列表
    const loadAgents = async () => {
      try {
        agents.value = await UserService.listAgents()
      } catch (error) {
        console.error('加载技术人员列表失败:', error)
      }
    }

    // 更新状态
    const updateStatus = async () => {
      try {
        updating.value = true
        await TicketService.updateStatus(ticketId, statusForm.value.status, statusForm.value.note)
        ElMessage.success('状态更新成功')
        statusDialog.value.visible = false
        await loadTicket()
      } catch (error) {
        ElMessage.error('状态更新失败: ' + error.message)
      } finally {
        updating.value = false
      }
    }

    // 分配工单
    const assignTicket = async () => {
      try {
        assigning.value = true
        const agent = agents.value.find(a => a.id === assignDialog.value.agentId)
        await TicketService.assign(ticketId, agent.id, agent.fullName)
        ElMessage.success('工单分配成功')
        assignDialog.value.visible = false
        await loadTicket()
      } catch (error) {
        ElMessage.error('工单分配失败: ' + error.message)
      } finally {
        assigning.value = false
      }
    }

    // 更新优先级
    const updatePriority = async () => {
      try {
        updatingPriority.value = true
        await TicketService.updatePriority(ticketId, priorityDialog.value.priority)
        ElMessage.success('优先级更新成功')
        priorityDialog.value.visible = false
        await loadTicket()
      } catch (error) {
        ElMessage.error('优先级更新失败: ' + error.message)
      } finally {
        updatingPriority.value = false
      }
    }

    // 添加评论
    const addComment = async () => {
      try {
        addingComment.value = true
        await CommentService.create(ticketId, commentForm.value)
        ElMessage.success('评论添加成功')
        commentDialog.value.visible = false
        commentForm.value = { content: '', commentType: 'PUBLIC' }
        await loadComments()
      } catch (error) {
        ElMessage.error('添加评论失败: ' + error.message)
      } finally {
        addingComment.value = false
      }
    }

    // 点赞评论
    const likeComment = async (commentId) => {
      try {
        await CommentService.likeComment(commentId)
        await loadComments()
      } catch (error) {
        ElMessage.error('点赞失败: ' + error.message)
      }
    }

    // 显示对话框
    const showStatusUpdateDialog = () => {
      statusForm.value.status = ticket.value.status
      statusForm.value.note = ''
      statusDialog.value.visible = true
    }

    const showAssignDialog = () => {
      assignDialog.value.agentId = ticket.value.assignedTo?.id || null
      assignDialog.value.visible = true
    }

    const showPriorityUpdateDialog = () => {
      priorityDialog.value.priority = ticket.value.priority
      priorityDialog.value.visible = true
    }

    const showCommentDialog = () => {
      commentForm.value = { content: '', commentType: 'PUBLIC' }
      commentDialog.value.visible = true
    }

    // 工具方法
    const getStatusType = (status) => {
      const types = {
        'OPEN': 'warning',
        'IN_PROGRESS': 'primary',
        'RESOLVED': 'success',
        'CLOSED': 'info'
      }
      return types[status] || 'info'
    }

    const getPriorityType = (priority) => {
      const types = {
        'LOW': 'info',
        'MEDIUM': 'warning',
        'HIGH': 'danger',
        'URGENT': 'danger'
      }
      return types[priority] || 'info'
    }

    const getHistoryType = (actionType) => {
      const types = {
        'CREATED': 'primary',
        'STATUS_CHANGED': 'success',
        'ASSIGNED': 'warning',
        'PRIORITY_CHANGED': 'info'
      }
      return types[actionType] || 'info'
    }

    const translateStatus = (status) => {
      const statusMap = {
        'OPEN': '待处理',
        'IN_PROGRESS': '处理中',
        'RESOLVED': '已解决',
        'CLOSED': '已关闭'
      }
      return statusMap[status] || status
    }

    const translatePriority = (priority) => {
      const priorityMap = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
      }
      return priorityMap[priority] || priority
    }

    const formatDate = (timestamp) => {
      if (!timestamp) return '-'
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadTicket()
      loadAgents()
    })

    return { 
      ticket, 
      comments,
      ticketHistory,
      agents,
      loading,
      statusDialog,
      assignDialog,
      priorityDialog,
      commentDialog,
      statusForm, 
      commentForm,
      updating, 
      assigning,
      updatingPriority,
      addingComment,
      canUpdateStatus,
      canAssign,
      canUpdatePriority,
      updateStatus, 
      assignTicket,
      updatePriority,
      addComment,
      likeComment,
      showStatusUpdateDialog,
      showAssignDialog,
      showPriorityUpdateDialog,
      showCommentDialog,
      getStatusType,
      getPriorityType,
      getHistoryType,
      translateStatus, 
      translatePriority,
      formatDate,
      Edit,
      User,
      Flag,
      Plus,
      ThumbUp
    }
  }
}
</script>

<style scoped>
.ticket-detail-container {
  max-width: 1200px;
  margin: 0 auto; 
  padding: 20px;
}

.ticket-card {
  margin-bottom: 20px;
}

.ticket-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.ticket-title-section h2 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.ticket-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.ticket-number {
  color: #909399;
  font-size: 14px;
}

.ticket-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.ticket-content {
  margin-top: 20px;
}

.section-card {
  margin-bottom: 20px;
}

.section-card h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.description-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

.description-detail {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.description-detail h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.detail-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.comments-header h3 {
  margin: 0;
}

.comments-list {
  max-height: 600px;
  overflow-y: auto;
}

.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-actions {
  display: flex;
  gap: 8px;
}

.comment-content {
  line-height: 1.6;
  color: #606266;
  margin-bottom: 8px;
}

.comment-edited {
  color: #909399;
  font-size: 12px;
  font-style: italic;
}

.info-card {
  margin-bottom: 20px;
}

.info-card h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.history-content {
  padding: 8px 0;
}

.history-content strong {
  color: #303133;
  font-size: 14px;
}

.history-content p {
  margin: 4px 0 0 0;
  color: #606266;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ticket-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .ticket-actions {
    justify-content: flex-start;
  }
  
  .ticket-detail-container {
    padding: 12px;
  }
}
</style>